const model = require('../model/AdminModel')
const {genToken, verifyToken} = require('../utils/token.js')
const md5 = require("md5");
let {PASSWORD_SALT, FAIL_RESPONSE, PORT, SUCCESS_RESPONSE, HOST} = require("../config");
const executeSql = require('../utils/query.js')
const path = require('path')
let fs = require('fs')

// 登录
exports.login = async (req, res) => {
    let {username, password} = req.body
    // 真实业务中，肯定要去数据库中匹配
    let findUser = await model.Login(username, password)
    if (findUser.length > 0) {
        // 找到了，要生成JWT用户登录态（token字符串），返回给前端
        // '15000ms' '3h'
        let accessToken = genToken(
            {admin_id: findUser[0].admin_id, username: findUser[0].username},
            '3h'
        )
        let refreshToken = genToken(
            {admin_id: findUser[0].admin_id, username: findUser[0].username},
            '15d'
        )
        res.json({
            msg: '登录成功',
            data: {accessToken, refreshToken},
            code: '00000',
        })
    } else {
        res.json({msg: '用户名或密码错误', code: '00001'})
    }
}

// 修改密码
exports.changePassword = async (req, res) => {
    let {oldPassword, newPassword} = req.body
    // 获取当前用户id
    let admin_id = req.admin_id
    // 加密新旧密码
    let EncryptOldPassword = md5(oldPassword + PASSWORD_SALT)
    let EncryptNewPassword = md5(newPassword + PASSWORD_SALT)

    // 判断旧密码是否正确
    let pwdState = await model.getUserPasswordAndId(admin_id, EncryptOldPassword)
    if (pwdState.length > 0) {
        // 旧密码正确，更改密码
        let result = await model.updatePasswordById(admin_id, EncryptOldPassword, EncryptNewPassword)
        if (result.affectedRows > 0) {
            res.json(SUCCESS_RESPONSE({}, '密码更改成功'))
        } else {
            res.json(FAIL_RESPONSE({}, '服务器繁忙', '00012'))
        }
    } else {
        // 旧密码错误
        res.json(FAIL_RESPONSE({}, '旧密码错误', '00011'))
    }
}

// 更改头像
exports.updateAvatar = async (req, res) => {
    // 1. 接收头像地址
    let {avatar} = req.body
    // 2. 将当前授权token中的admin_id进行更新
    let admin_id = req.admin_id
    // 3. 调用模型更新头像
    await model.updateAvatar(admin_id, avatar)
    res.json(SUCCESS_RESPONSE({}, '更新用户头像成功'))
}

// 文件上传
exports.upload = (req, res) => {
    // console.log(req.body) //接收文本信息
    console.log(req.file) //接收文件信息
    // 判断是否有文件上传
    if (req.file) {
        // 进行文件的重命名即可 fs.rename
        let {originalname, destination, filename} = req.file
        let dotIndex = originalname.lastIndexOf('.')
        let ext = originalname.substring(dotIndex)
        let oldPath = `${destination}${filename}`
        let newPath = `${destination}${filename}${ext}`
        fs.rename(oldPath, newPath, (err) => {
            if (err) {
                throw err
            }
            res.json({
                msg: '上传文件成功',
                data: {path: `${newPath}`, server_url: `http://127.0.0.1:${PORT}/`},
                code: '00000',
            })
        })
    } else {
        res.json({msg: '没有文件', data: {}, code: '00089'})
    }
}

// 获取管理员信息
exports.adminInfo = async (req, res) => {
    // 1.获取用户id
    let admin_id = req.admin_id

    let data = await model.getUserInfo(admin_id)

    data[0].avatar = `http://127.0.0.1:${PORT}/` + data[0].avatar

    let userInfo = {
        code: '00000',
        data: {...data[0]},
        msg: '获取管理员信息成功',
    }
    res.json(userInfo)
}

// 获取管理员列表
exports.adminList = async (req, res) => {
    // 1. 调用模型，获取管理员列表数据
    let result = await model.getAdminList()
    // 2. 响应给前端
    res.json({code: '00000', msg: '获取管理员列表成功', data: result})
}

// 刷新token
exports.refreshToken = async (req, res) => {
    let {refreshToken} = req.body

    // 1. 验证refreshToken中的有效期
    let userInfo = verifyToken(refreshToken)
    if (userInfo === false) {
        // refreshToken失效了
        res.status(401).json({msg: '用户refreshToken刷新失败', code: 'A0231'})
        return
    }
    // 2. 获取refreshToken中的用户信息,要去数据库查询最新的用户信息
    let result = await model.getUserInfoById(userInfo.admin_id)
    if (result.length > 0) {
        let token = genToken(
            {admin_id: result[0].admin_id, username: result[0].username},
            '3h'
        )
        // 3. 重新再生成新token并返回给前端
        res.json({
            msg: '刷新token成功',
            data: {accessToken: token, refreshToken},
            code: '00000',
        })
    } else {
        res.json({
            message: '用户信息有误',
            code: 20003,
        })
    }
}

// 定义uploads目录路径
const UPLOADS_DIR = path.join(__dirname, '../uploads')

// 获取所有图片文件的
exports.getImages = (req, res) => {
    // 读取uploads目录
    fs.readdir(UPLOADS_DIR, (err, files) => {
        // 过滤出图片文件（可以根据需要扩展支持的格式）
        const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp']
        const imageFiles = files.filter((file) => {
            const ext = path.extname(file).toLowerCase()
            return imageExtensions.includes(ext)
        })

        // 构建完整的URL路径
        const baseUrl = `${HOST}:${PORT}/uploads/`
        const imageUrls = imageFiles.map((file) => ({
            name: file,
            url: baseUrl + file,
        }))

        // 返回JSON响应
        res.json({
            code: '00000',
            data: {
                count: imageUrls.length,
                images: imageUrls,
            },
            msg: '请求成功',
        })
    })
}

// 删除指定图片文件
exports.delImages = (req, res) => {
    const { filename } = req.query

    // 验证请求参数
    if (!filename) {
        return res.status(400).json({
            error: 'Filename is required',
        })
    }

    // 构建文件路径
    const filePath = path.join(UPLOADS_DIR, filename)

    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
        return res.status(404).json({
            msg: 'File not found',
        })
    }

    // 删除文件
    fs.unlink(filePath, (err) => {
        if (err) {
            console.error('Error deleting file:', err)
            return res.status(500).json({
                msg: 'Failed to delete file',
            })
        }

        res.json({
            code: '00000',
            msg: 'File deleted successfully',
            data: filename,
        })
    })
}

